package com.macro.mall.demo.service.impl;

import com.macro.mall.demo.dto.EsIndexDto;
import com.macro.mall.demo.service.EsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @Author：尚志豪
 * @Package：com.macro.mall.demo.service.impl
 * @Project：mall-swarm-B
 * @name：EsServiceImpl
 * @Date：2024/10/25 20:38
 */
@Service
@Slf4j
public class EsServiceImpl implements EsService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
     * 创建索引
     * @param esIndexDto
     * @return
     */
    @Override
    public void indexCreate(EsIndexDto esIndexDto) {
        // 检查索引是否已存在
        if (isExistIndex(esIndexDto.getIndexName())){
            throw new RuntimeException("索引已经存在: "+ esIndexDto.getIndexName());
        }

        // 创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(esIndexDto.getIndexName());

        // 设置索引配置
        if (StringUtils.isNoneBlank(esIndexDto.getIndexMappings())){
            request.mapping(esIndexDto.getIndexMappings(), XContentType.JSON);
        }

        // 执行创建索引操作
        try {
            restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            log.info("索引创建成功: {}",esIndexDto.getIndexName());
        } catch (IOException e) {
            log.error("创建索引失败, 错误信息: {}", e.getMessage());
            throw new RuntimeException("创建索引失败: " + esIndexDto.getIndexName(), e);
        }
    }
    /**
     * 判断索引是否存在
     * @param indexName
     * @return
     */
    @Override
    public Boolean isExistIndex(String indexName) {
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        try {
            Boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            return exists;
        } catch (Exception e) {
            log.error("异常，索引为空:{}",e.getMessage());
        }
        return false;
    }
    /**
     * 删除索引
     * @param indexName
     * @return
     */
    @Override
    public void deleteIndex(String indexName) {
        DeleteIndexRequest deleteIndexRequest = null;

        // 创建es请求
        if (!isExistIndex(indexName)){
            throw new RuntimeException("索引不存在："+indexName);
        }
        deleteIndexRequest = new DeleteIndexRequest(indexName);
        try {
            restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
            log.info("删除成功，索引:{}",indexName);
        } catch (IOException e) {
            log.error("删除索引失败, 错误信息: {}",e.getMessage());
            throw new RuntimeException(e);
        }

    }
    /**
     * 查询索引
     * @param indexName
     * @return
     */
    @Override
    public Map<String, Object> getIndex(String indexName) {
        if (!isExistIndex(indexName)){
            throw new RuntimeException("索引不存在:"+indexName);
        }

        //创建查询
        GetIndexRequest indexRequest = new GetIndexRequest(indexName);

        try {
            GetIndexResponse response = restHighLevelClient.indices().get(indexRequest, RequestOptions.DEFAULT);
            log.info("获取索引映射成功:{}",indexName);
            return response.getMappings().get(indexName).sourceAsMap();
        } catch (IOException e) {
            log.error("获取索引映射失败, 错误信息: {}", e.getMessage());
            throw new RuntimeException("索引映射失败:" +indexName ,e);
        }


    }

    /**
     * 修改索引
     * @param esIndexDto
     */
    @Override
    public void updIndex(EsIndexDto esIndexDto) {

        //判断索引是否存在
        if (!isExistIndex(esIndexDto.getIndexName())){
            throw new RuntimeException("索引不存在"+esIndexDto.getIndexName());
        }
        // 创建索引请求
        UpdateSettingsRequest request = new UpdateSettingsRequest(esIndexDto.getIndexName());

        // 更新索引
        if (StringUtils.isNoneBlank(esIndexDto.getIndexMappings())) {
            request.settings(esIndexDto.getIndexMappings(),XContentType.JSON);
        }

        // 执行更新索引设置操作
        try {
            boolean b = restHighLevelClient.indices().putSettings(request,RequestOptions.DEFAULT).isAcknowledged();
            if (b){
                log.info("索引设置更新成功:{}",esIndexDto.getIndexName());
            }else {
                log.warn("索引设置未更新成功:{}",esIndexDto.getIndexName());
            }
        } catch (IOException e) {
            log.error("更新索引设置失败, 错误信息: {}",e.getMessage());
            throw new RuntimeException(e);
        }

    }
}
